<template>
    <div class="auth-container">
      <bk-animation></bk-animation>
      <div class="auth-box forgot-box">
        <div class="auth-header">
          <div class="logo-container">
            <img src="/logo.png" alt="Logo" class="logo" />
          </div>
          <h1 class="title">找回密码</h1>
          <p class="subtitle">我们将向您的邮箱发送重置密码的链接</p>
        </div>
  
        <div class="steps-container">
          <div class="steps">
            <div class="step" :class="{ 'active': currentStep >= 1, 'completed': currentStep > 1 }">
              <div class="step-number">1</div>
              <div class="step-label">验证邮箱</div>
            </div>
            <div class="step-line"></div>
            <div class="step" :class="{ 'active': currentStep >= 2, 'completed': currentStep > 2 }">
              <div class="step-number">2</div>
              <div class="step-label">验证码确认</div>
            </div>
            <div class="step-line"></div>
            <div class="step" :class="{ 'active': currentStep >= 3, 'completed': currentStep > 3 }">
              <div class="step-number">3</div>
              <div class="step-label">重置密码</div>
            </div>
          </div>
        </div>
  
        <!-- 步骤1：输入邮箱 -->
        <el-form v-if="currentStep === 1" :model="forgotForm" :rules="emailRules" ref="emailFormRef" class="auth-form">
          <el-form-item prop="email">
            <div class="input-icon-wrapper">
              <el-icon class="input-icon"><Message /></el-icon>
              <el-input 
                v-model="forgotForm.email" 
                placeholder="请输入注册邮箱" 
                size="large"
                class="auth-input" 
              />
            </div>
          </el-form-item>
  
          <el-button 
            type="primary" 
            size="large" 
            class="auth-btn" 
            :loading="loading" 
            @click="verifyEmail"
          >
            下一步
          </el-button>
        </el-form>
  
        <!-- 步骤2：输入验证码 -->
        <el-form v-if="currentStep === 2" :model="forgotForm" :rules="codeRules" ref="codeFormRef" class="auth-form">
          <div class="verification-message">
            <el-icon class="message-icon"><InfoFilled /></el-icon>
            <p>验证码已发送至 <strong>{{ maskEmail(forgotForm.email) }}</strong></p>
          </div>
  
          <el-form-item prop="code">
            <div class="verification-code-container">
              <input 
                v-for="(digit, index) in 6" 
                :key="index"
                ref="codeInputs"
                v-model="verificationDigits[index]"
                class="verification-digit"
                maxlength="1"
                @input="handleDigitInput(index)"
                @keydown="handleDigitKeydown($event, index)"
                @paste="handlePaste"
              />
            </div>
          </el-form-item>
  
          <div class="resend-container">
            <span v-if="codeCountdown > 0">{{ codeCountdown }}秒后可重新发送</span>
            <a v-else href="#" class="resend-link" @click.prevent="resendCode">重新发送验证码</a>
          </div>
  
          <el-button 
            type="primary" 
            size="large" 
            class="auth-btn" 
            :loading="loading" 
            @click="verifyCode"
          >
            验证
          </el-button>
        </el-form>
  
        <!-- 步骤3：重置密码 -->
        <el-form v-if="currentStep === 3" :model="resetForm" :rules="passwordRules" ref="passwordFormRef" class="auth-form">
          <el-form-item prop="password">
            <div class="input-icon-wrapper">
              <el-icon class="input-icon"><Lock /></el-icon>
              <el-input 
                v-model="resetForm.password" 
                type="password" 
                placeholder="请输入新密码" 
                size="large"
                show-password
                class="auth-input" 
              />
            </div>
          </el-form-item>
  
          <el-form-item prop="confirmPassword">
            <div class="input-icon-wrapper">
              <el-icon class="input-icon"><Check /></el-icon>
              <el-input 
                v-model="resetForm.confirmPassword" 
                type="password" 
                placeholder="请确认新密码" 
                size="large"
                show-password
                class="auth-input" 
              />
            </div>
          </el-form-item>
  
          <div class="password-strength" v-if="resetForm.password">
            <div class="strength-label">密码强度：</div>
            <div class="strength-meter">
              <div class="strength-bar" :class="passwordStrengthClass"></div>
            </div>
            <div class="strength-text" :class="passwordStrengthClass">{{ passwordStrengthText }}</div>
          </div>
  
          <el-button 
            type="primary" 
            size="large" 
            class="auth-btn" 
            :loading="loading" 
            @click="resetPassword"
          >
            重置密码
          </el-button>
        </el-form>
  
        <!-- 步骤4：成功页面 -->
        <div v-if="currentStep === 4" class="success-container">
          <div class="success-icon">
            <el-icon><CircleCheckFilled /></el-icon>
          </div>
          <h2 class="success-title">密码重置成功</h2>
          <p class="success-message">您的密码已成功重置，请使用新密码登录</p>
          <el-button 
            type="primary" 
            size="large" 
            class="auth-btn" 
            @click="goToLogin"
          >
            返回登录
          </el-button>
        </div>
  
        <div class="auth-footer" v-if="currentStep !== 4">
          <span>记起密码了？</span>
          <router-link to="/login" class="auth-link">立即登录</router-link>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Message, Lock, Check, InfoFilled, CircleCheckFilled } from '@element-plus/icons-vue'
  import bkAnimation from '../components/bkAnimation.vue'
  import network from '../api/index'
  import { useRouter } from 'vue-router'
  
  const router = useRouter()
  const loading = ref(false)
  const currentStep = ref(1)
  const codeCountdown = ref(0)
  const emailFormRef = ref(null)
  const codeFormRef = ref(null)
  const passwordFormRef = ref(null)
  const codeInputs = ref([])
  const verificationDigits = ref(['', '', '', '', '', ''])
  const { communityApi,userApi,request } = network
  const forgotForm = reactive({
    email: '',
    code: ''
  })
  
  const resetForm = reactive({
    password: '',
    confirmPassword: ''
  })
  
  // 邮箱验证规则
  const emailRules = {
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ]
  }
  
  // 验证码规则
  const codeRules = {
    code: [
      { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
  }
  
  // 密码验证规则
  const validatePass = (rule, value, callback) => {
    if (value !== resetForm.password) {
      callback(new Error('两次输入密码不一致'))
    } else {
      callback()
    }
  }
  
  const passwordRules = {
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validatePass, trigger: 'blur' }
    ]
  }
  
  // 密码强度计算
  const passwordStrength = computed(() => {
    const password = resetForm.password
    if (!password) return 0
    
    let strength = 0
    
    // 长度检查
    if (password.length >= 8) strength += 1
    if (password.length >= 12) strength += 1
    
    // 复杂度检查
    if (/[A-Z]/.test(password)) strength += 1
    if (/[a-z]/.test(password)) strength += 1
    if (/[0-9]/.test(password)) strength += 1
    if (/[^A-Za-z0-9]/.test(password)) strength += 1
    
    return Math.min(strength, 4)
  })
  
  const passwordStrengthClass = computed(() => {
    const strength = passwordStrength.value
    if (strength <= 1) return 'weak'
    if (strength === 2) return 'medium'
    if (strength === 3) return 'strong'
    return 'very-strong'
  })
  
  const passwordStrengthText = computed(() => {
    const strength = passwordStrength.value
    if (strength <= 1) return '弱'
    if (strength === 2) return '中'
    if (strength === 3) return '强'
    return '非常强'
  })
  
  // 邮箱掩码处理
  const maskEmail = (email) => {
    if (!email) return ''
    const parts = email.split('@')
    if (parts.length !== 2) return email
    
    const name = parts[0]
    const domain = parts[1]
    
    let maskedName = name
    if (name.length > 3) {
      maskedName = name.substring(0, 2) + '*'.repeat(name.length - 3) + name.substring(name.length - 1)
    } else if (name.length > 1) {
      maskedName = name.substring(0, 1) + '*'.repeat(name.length - 1)
    }
    
    return `${maskedName}@${domain}`
  }
  
  // 验证码输入处理
  const handleDigitInput = (index) => {
    // 自动聚焦下一个输入框
    if (verificationDigits.value[index] && index < 5) {
      nextTick(() => {
        codeInputs.value[index + 1].focus()
      })
    }
    
    // 更新完整验证码
    forgotForm.code = verificationDigits.value.join('')
  }
  
  const handleDigitKeydown = (event, index) => {
    // 处理退格键
    if (event.key === 'Backspace' && !verificationDigits.value[index] && index > 0) {
      verificationDigits.value[index - 1] = ''
      nextTick(() => {
        codeInputs.value[index - 1].focus()
      })
    }
  }
  
  const handlePaste = (event) => {
    event.preventDefault()
    const pastedData = (event.clipboardData || window.clipboardData).getData('text')
    const digits = pastedData.replace(/\D/g, '').substring(0, 6).split('')
    
    digits.forEach((digit, index) => {
      if (index < 6) {
        verificationDigits.value[index] = digit
      }
    })
    
    forgotForm.code = verificationDigits.value.join('')
    
    // 如果粘贴的内容填满了所有输入框，聚焦到最后一个
    if (digits.length === 6) {
      nextTick(() => {
        codeInputs.value[5].focus()
      })
    } else if (digits.length > 0) {
      // 否则聚焦到下一个空输入框
      nextTick(() => {
        codeInputs.value[digits.length].focus()
      })
    }
  }
  
  // 步骤1：验证邮箱
  const verifyEmail = async () => {
    if (!emailFormRef.value) return
    try {
      await emailFormRef.value.validate()
      loading.value = true
      console.log(forgotForm)
      // 发送验证码
      await request(userApi.forgot,{email:forgotForm.email})
      // 启动倒计时
      codeCountdown.value = 60
      const timer = setInterval(() => {
        codeCountdown.value--
        if (codeCountdown.value <= 0) clearInterval(timer)
      }, 1000)
      
      ElMessage.success('验证码已发送')
      currentStep.value = 2
      // 聚焦第一个验证码输入框
      nextTick(() => {
        if (codeInputs.value[0]) {
          codeInputs.value[0].focus()
        }
      })
    } catch (error) {
      if (error?.message) {
        ElMessage.error(error.message)
      }
    } finally {
      loading.value = false
    }
  }
  // 重新发送验证码
  const resendCode = async () => {
    try {
      loading.value = true
      await request(userApi.forgot,{ email: forgotForm.email },'get')
      
      // 重置验证码输入
      verificationDigits.value = ['', '', '', '', '', '']
      forgotForm.code = ''
      
      // 启动倒计时
      codeCountdown.value = 60
      const timer = setInterval(() => {
        codeCountdown.value--
        if (codeCountdown.value <= 0) clearInterval(timer)
      }, 1000)
      
      ElMessage.success('验证码已重新发送')
      
      // 聚焦第一个验证码输入框
      nextTick(() => {
        if (codeInputs.value[0]) {
          codeInputs.value[0].focus()
        }
      })
    } catch (error) {
      if (error?.message) {
        ElMessage.error(error.message)
      }
    } finally {
      loading.value = false
    }
  }
  
  // 步骤2：验证验证码
  const verifyCode = async () => {
    if (forgotForm.code.length !== 6) {
      return ElMessage.warning('请输入6位验证码')
    }
    try {
      loading.value = true
      // 验证验证码
      const data =await request(userApi.validateCode,forgotForm)
      ElMessage.success('验证码验证成功')
      currentStep.value = 3
    } catch (error) {
        ElMessage.error(error)
    } finally {
      loading.value = false
    }
  }
  // 步骤3：重置密码
  const resetPassword = async () => {
    if (!passwordFormRef.value) return
    try {
      await passwordFormRef.value.validate()
      loading.value = true
      // 重置密码
      await request(userApi.reset,{
        email: forgotForm.email,
        code: forgotForm.code,
        password: resetForm.password
      },"POST")
      ElMessage.success('密码重置成功')
      currentStep.value = 4
    } catch (error) {
        ElMessage.error(error)
    } finally {
      loading.value = false
    }
  }
  // 返回登录页
  const goToLogin = () => {
    router.push('/login')
  }
  </script>
  
  <style scoped lang="scss">
  // 主题颜色
  $primary-color: #66a6ff;
  $primary-gradient: linear-gradient(120deg, #89f7fe 0%, #66a6ff 100%);
  $text-color: #2c3e50;
  $text-secondary: #606266;
  $border-color: #e5e7eb;
  $background-color: white;
  $shadow-color: rgba(0, 0, 0, 0.1);
  $success-color: #67c23a;
  
  .auth-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    height: 90vh;
  }
  
  .auth-box {
    z-index: 1;
    width: 480px;
    padding: 40px;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    background-color: white;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 6px;
      background: $primary-gradient;
    }
  }
  
  .forgot-box {
    max-width: 520px;
  }
  
  .auth-header {
    text-align: center;
    margin-bottom: 30px;
    
    .logo-container {
      margin-bottom: 20px;
      
      .logo {
        height: 60px;
        object-fit: contain;
      }
    }
    
    .title {
      color: $text-color;
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 10px;
    }
    
    .subtitle {
      color: $text-secondary;
      font-size: 16px;
    }
  }
  
  .steps-container {
    margin-bottom: 30px;
    
    .steps {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .step {
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        
        .step-number {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #f5f7fa;
          color: $text-secondary;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          margin-bottom: 8px;
          border: 2px solid #f5f7fa;
          transition: all 0.3s ease;
        }
        
        .step-label {
          font-size: 14px;
          color: $text-secondary;
          transition: all 0.3s ease;
        }
        
        &.active {
          .step-number {
            background-color: rgba($primary-color, 0.1);
            color: $primary-color;
            border-color: $primary-color;
          }
          
          .step-label {
            color: $primary-color;
            font-weight: 500;
          }
        }
        
        &.completed {
          .step-number {
            background-color: $primary-color;
            color: white;
            border-color: $primary-color;
          }
        }
      }
      
      .step-line {
        flex: 1;
        height: 2px;
        background-color: #f5f7fa;
        margin: 0 10px;
        margin-bottom: 24px;
      }
    }
  }
  
  .auth-form {
    margin-bottom: 20px;
  }
  
  .input-icon-wrapper {
    position: relative;
    
    .input-icon {
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
      color: $primary-color;
      z-index: 2;
      font-size: 18px;
    }
    
    .auth-input {
      :deep(.el-input__wrapper) {
        padding-left: 40px;
        border-radius: 12px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
        
        &:hover {
          box-shadow: 0 4px 12px rgba(102, 166, 255, 0.2);
        }
        
        &.is-focus {
          box-shadow: 0 0 0 2px rgba(102, 166, 255, 0.2);
        }
      }
    }
  }
  
  .verification-message {
    display: flex;
    align-items: center;
    background-color: rgba($primary-color, 0.1);
    padding: 15px;
    border-radius: 12px;
    margin-bottom: 20px;
    
    .message-icon {
      color: $primary-color;
      font-size: 20px;
      margin-right: 10px;
    }
    
    p {
      margin: 0;
      color: $text-color;
      font-size: 14px;
      
      strong {
        font-weight: 600;
      }
    }
  }
  
  .verification-code-container {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .verification-digit {
      width: 50px;
      height: 60px;
      border-radius: 12px;
      border: 2px solid $border-color;
      background-color: white;
      font-size: 24px;
      font-weight: 600;
      text-align: center;
      transition: all 0.3s ease;
      
      &:focus {
        border-color: $primary-color;
        box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
        outline: none;
      }
    }
  }
  
  .resend-container {
    text-align: center;
    margin-bottom: 20px;
    font-size: 14px;
    color: $text-secondary;
    
    .resend-link {
      color: $primary-color;
      text-decoration: none;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  .password-strength {
    margin-bottom: 20px;
    
    .strength-label {
      font-size: 14px;
      color: $text-secondary;
      margin-bottom: 8px;
    }
    
    .strength-meter {
      height: 6px;
      background-color: #f5f7fa;
      border-radius: 3px;
      overflow: hidden;
      margin-bottom: 8px;
      
      .strength-bar {
        height: 100%;
        border-radius: 3px;
        transition: all 0.3s ease;
        
        &.weak {
          width: 25%;
          background-color: #f56c6c;
        }
        
        &.medium {
          width: 50%;
          background-color: #e6a23c;
        }
        
        &.strong {
          width: 75%;
          background-color: #67c23a;
        }
        
        &.very-strong {
          width: 100%;
          background-color: #67c23a;
        }
      }
    }
    
    .strength-text {
      font-size: 12px;
      text-align: right;
      
      &.weak {
        color: #f56c6c;
      }
      
      &.medium {
        color: #e6a23c;
      }
      
      &.strong, &.very-strong {
        color: #67c23a;
      }
    }
  }
  
  .success-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 20px 0;
    
    .success-icon {
      font-size: 80px;
      color: $success-color;
      margin-bottom: 20px;
    }
    
    .success-title {
      font-size: 24px;
      font-weight: 600;
      color: $text-color;
      margin-bottom: 10px;
    }
    
    .success-message {
      color: $text-secondary;
      margin-bottom: 30px;
    }
  }
  
  .auth-btn {
    width: 100%;
    height: 50px;
    font-size: 16px;
    font-weight: 500;
    letter-spacing: 2px;
    border: none;
    background-image: $primary-gradient;
    border-radius: 12px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(102, 166, 255, 0.3);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
  
  .auth-footer {
    margin-top: 20px;
    text-align: center;
    font-size: 14px;
    color: $text-secondary;
    
    .auth-link {
      color: $primary-color;
      text-decoration: none;
      font-weight: 500;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  /* 响应式设计 */
  @media (max-width: 576px) {
    .auth-box {
      width: 100%;
      padding: 30px 20px;
    }
    
    .auth-header {
      .title {
        font-size: 24px;
      }
      
      .subtitle {
        font-size: 14px;
      }
    }
    
    .steps {
      .step {
        .step-number {
          width: 30px;
          height: 30px;
          font-size: 14px;
        }
        
        .step-label {
          font-size: 12px;
        }
      }
    }
    
    .verification-code-container {
      .verification-digit {
        width: 40px;
        height: 50px;
        font-size: 20px;
      }
    }
    
    .auth-btn {
      height: 46px;
      font-size: 15px;
    }
  }
  </style>